package edu.fiu.cis.nursing.server.db.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public final class HibernateTransaction {

	public static <O> O execute(ITransaction<O> transaction) {
		return execute(transaction, true);
	}

	public static <O> O execute(ITransaction<O> transaction, boolean refresh) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		boolean error = false;
		O o = null;
		try {
			tx = session.beginTransaction();
			o = transaction.execute(tx, session);

		} catch (HibernateException e) {
			e.printStackTrace();
			error = true;
			throw new RuntimeException(e);

		} catch (Exception e) {
			e.printStackTrace();
			error = true;
			throw new RuntimeException(e);

		} finally {
			try {
				if (error) {
					if (tx != null && tx.isActive())
						tx.rollback();
				} else {
					tx.commit();
					// session.refresh(o);
				}
				HibernateUtil.closeSession(session);
			} catch (HibernateException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return o;
	}

}
